﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.Core
{
    public class RepositoryFactory
    {
        public static T Create<T>()
        {
            try
            {
                Type type = typeof(T);
                string RepositoryConfigFile = System.Configuration.ConfigurationManager.AppSettings["RepositoryConfigFile"];
                DataSet ds = new DataSet();
                ds.ReadXml(GetRepositoryFilePath(RepositoryConfigFile));
                DataRow[] drs = ds.Tables["Repository"].Select("Name = '" + type.Name + "'");
                if (drs.Length > 0)
                {
                    string strAssembly = drs[0]["Assembly"].ToString();
                    string strType = drs[0]["Type"].ToString();
                    Assembly asm = Assembly.Load(strAssembly);
                    T retObj = (T)asm.CreateInstance(strAssembly + "." + strType, true);
                    return retObj;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return default(T);
        }

        private static string GetRepositoryFilePath(string relativePath)
        {
            if (System.Web.HttpContext.Current == null)
            {
                return relativePath.Replace("~", AppDomain.CurrentDomain.BaseDirectory);
            }
            return System.Web.HttpContext.Current.Server.MapPath(relativePath);
        }
    }
}
